package com.cjym.GateWay.filters;

import com.cjym.GateWay.interfaces.PermissionAuthentication;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Slf4j
@Component
@ConditionalOnProperty(name = "gateway.permission.enable", havingValue = "true")
public class PermissionAuthenticationFilter implements GlobalFilter, Ordered{
    @Value("${permission.authentication.impl:#{'defaultPermissionAuthentication'}}")
    private String permissionAuthenticationImplName;

    @Resource
    private ApplicationContext context;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        PermissionAuthentication permissionAuthentication = null;
        Object bean = context.getBean(permissionAuthenticationImplName);
        if(bean instanceof PermissionAuthentication) permissionAuthentication = (PermissionAuthentication) bean;
        else log.error("权限实现类错误:{}",permissionAuthenticationImplName);
        if (permissionAuthentication != null && permissionAuthentication.release()) return chain.filter(exchange);
        else log.error("权限校验失败，权限实现为:{}",permissionAuthenticationImplName);
        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return 4;
    }

    @PostConstruct
    private void init() {
        log.info("权限校验过滤器初始化完成，权限实现为:{}",permissionAuthenticationImplName);
    }
}
